const { resolve } = require('path')

const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken')

const { SECRET } = require(resolve(__dirname, '../config/default'))

// 结果处理
const jgcl = (ctx, code = 200, msg, data = null) => {
  const res = {
    status: {
      code,
      msg
    },
    data
  }
  ctx.body = JSON.stringify(res)
}

// 密码加密
const passwordEncryption = (password) => {
  let salt = bcrypt.genSaltSync(10); // 生成盐
  let hash = bcrypt.hashSync(password, salt); // 加密

  return hash
}

// 密码验证
const passwordVerify = (password, pwd) => {
  const res = bcrypt.compareSync(password, pwd)

  return res
}

// 生成token
const createToken = (data) => {
  let token = jwt.sign(
    { data },
    SECRET,//秘钥
    {
      expiresIn: '24h', //有效期 "2 days""10h""7d""120""120ms"
    }
  )

  return token
}


module.exports = {
  jgcl,
  passwordEncryption,
  passwordVerify,
  createToken
}